package com.alex.wechat.mp.handler;

import java.util.Map;

import org.jeecgframework.core.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alex.wechat.core.handler.WxHandler;
import com.alex.wechat.mp.config.WxConsts;
import com.alex.wechat.mp.message.mass.entity.WxMassBillEntity;
import com.alex.wechat.mp.message.mass.service.WxMassBillServiceI;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.message.bean.WxXmlMessage;
import me.chanjar.weixin.message.rule.WxMessageHandler;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * 群发消息完成处理器
 * 
 * @author Debenson
 * @since 0.1
 */
@WxHandler(value = WxConsts.EVT_MASS_SEND_JOB_FINISH)
public class MassSendFinishHandler implements WxMessageHandler {
  private static final Logger logger = LoggerFactory.getLogger(MassSendFinishHandler.class);

  @Autowired
  private WxMassBillServiceI massBillService;

  @Override
  public String handle(WxXmlMessage wxMessage, Map<String, Object> context)
      throws WxErrorException {
    try {
      saveMassBill(wxMessage);
    } catch (Exception e) {
      logger.error("回写群发单失败", e);
    }
    WxMpXmlOutMessage m = WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
    return m.toXml();
  }

  /**
   * 保存接收到的信息
   * 
   * @param msg
   * @throws BusinessException
   */
  private void saveMassBill(WxMpXmlMessage msg) throws BusinessException {
    WxMassBillEntity massBill = massBillService.getByMsgId(msg.getMsgId().toString());
    if (massBill == null) {
      throw new BusinessException("找不到指定的群发单");
    }

    massBill.setSendStatus(msg.getStatus());
    massBill.setSendErrMsg(msg.getMsg());
    massBill.setTotalCount(msg.getTotalCount());
    massBill.setFilterCount(msg.getFilterCount());
    massBill.setSentCount(msg.getSentCount());
    massBill.setErrorCount(msg.getErrorCount());
    massBillService.save(massBill);
  }

}
